package myaction.teacher;

import myutil.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

public class TeacherOptCancalAction extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("TeacherOptCancalAction");
        request.setCharacterEncoding("utf-8");
        String id = request.getParameter("id");
        try {
            Connection conn = DbUtil.getConn();
            String sql = "select c_isable from t_courses where c_id=" + id + ";";
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery(sql);
            if (rs.next()) {
                if (rs.getInt(1) == 0) {
//                    如果c_isable为0,说明不能取消授课
                    request.setAttribute("CannotCancal", "此课程已开课，无法取消授课！");
                    request.getRequestDispatcher("TeacherOptFindAll").forward(request, response);
                } else {
//                    否则，取消授课。t_courses表的c_teacher_id变成0
                    String sql2 = "update t_courses set c_teacher_id=0,c_isable='0' where c_id=" + id + ";";
                    PreparedStatement ps = conn.prepareStatement(sql2);
                    ps.executeUpdate();
                    ps.close();
                }
            }
            rs.close();
            st.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        request.getRequestDispatcher("TeacherOptFindAll").forward(request, response);
    }

}
